package BLC

import (
	"bytes"
	"crypto/sha256"
	"fmt"
	"strconv"
	"time"
)

type Block struct{
	//时间戳，创建区块的时间
	TimeStamp int64
	//上一个区块的hash，父hash
	PreviewHash []byte
	//交易数据
	Data []byte
	//hash当前区块的hash
	Hash []byte
}

func (b *Block)SetHash(){
	//先将时间戳转化为字节数组
	str:=strconv.FormatInt(b.TimeStamp,10)
	TimeStamp:=[]byte(str)
	//把除Hash之外的其他的东西拼接起来（字节数组)
	headers:=bytes.Join([][]byte{TimeStamp,b.PreviewHash,b.Data},[]byte{})
	//进行hash256散列
	Hash:=sha256.Sum256(headers)
	b.Hash=Hash[:]
}

func NewBlock(data string,previewHash []byte)*Block{
	b:=&Block{
		TimeStamp:time.Now().Unix(),
		PreviewHash:previewHash,
		Data:[]byte(data),
		Hash:[]byte{},
	}
	b.SetHash()
	return b
}

func NewGenisBlock()*Block{
	return NewBlock("Genis Block",[]byte{})
}
func (b *Block)Print(){
	fmt.Printf("时间戳是:%s\n",time.Unix(b.TimeStamp,0).Format("2006-01-02 15:04:05.999999999"))
	fmt.Printf("前一个区块的hash是:%x\n",b.PreviewHash)
	fmt.Printf("交易的数据是:%s\n",b.Data)
	fmt.Printf("当前区块的hash是:%x\n",b.Hash)
}
